//
//  FamilyViewController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/20.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

protocol FamilyViewControllerDelegate: NSObjectProtocol {
    func familyVc(_ vc: FamilyViewController, didSelected vm: FamilyRowViewModel)
}

class FamilyViewController: BaseViewController {
    
    weak var delegate: FamilyViewControllerDelegate?
    
    var selectClosure: ((_ vm: FamilyRowViewModel) -> Void)?
    
    var fromProfile = false

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    private var viewModel: FamilyViewModel? {
        didSet {
            tableView.reloadData()
        }
    }
    
    private var cardVm = BindCardViewModel(model: BindCardModel())
    
    @IBOutlet private weak var activityView: UIActivityIndicatorView!

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.contentInset = UIEdgeInsets(top: 16, left: 0, bottom: 0, right: 0)
            tableView.backgroundColor = .background
            tableView.rowHeight = 138
            tableView.estimatedRowHeight = UITableView.automaticDimension
            tableView.tableFooterView = UIView()
            tableView.showsVerticalScrollIndicator = false
            tableView.showsHorizontalScrollIndicator = false
            tableView.register(FamilyViewCell.nibForCell(),
                               forCellReuseIdentifier: FamilyViewCell.reuseIdentifier())
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NotiName.loginSuccess, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}

private extension FamilyViewController {
    func setupUI() {
        title = "家庭成员"
        
        createRightBarBtnItem(title: "添加成员", method: #selector(addFamily))
        
        tableView.mj_header = refreshHeader(action: #selector(loadData))
        tableView.mj_header?.beginRefreshing()
    }
    
    func endRefresh() {
        tableView.mj_header?.endRefreshing()
    }
    
    @objc func addFamily() {
        Utilities.pushLoginVc(self)
        pushFamilyAddVc(FamilyRowViewModel(family: FamilyModel()), addType: .add)
    }
    
    @objc func loadData() {
        FamilyViewModel.getFamilyList(success: { models in
            self.endRefresh()
            self.viewModel = FamilyViewModel(models: models)
        }) { errorMsg in
            self.endRefresh()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    @objc func loginSuccess() {
        tableView.mj_header?.beginRefreshing()
    }
}

extension FamilyViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = FamilyViewCell.nibForCell().instantiate(withOwner: nil, options: nil)[0] as! FamilyViewCell
        
        
        //tableView.dequeueReusableCell(withIdentifier: FamilyViewCell.reuseIdentifier(),
//                                                  for: indexPath) as! FamilyViewCell
        if let vm = viewModel?.viewModel(for: indexPath) {
            cell.configure(with: vm, type: .family)
        }
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if fromProfile { return }
        
        guard let vm = viewModel?.viewModel(for: indexPath) else { return }
        
        switch vm.cardType {
        case .unbound: HUDTool.show(message: "请先去绑卡")
        default:
            delegate?.familyVc(self, didSelected: vm)
            navigationController?.popViewController(animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return false
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        YSGLog(indexPath.row)
    }
    
}

extension FamilyViewController: FamilyViewCellDelegate {
    func familyViewCell(willEdit cell: FamilyViewCell) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(for: indexPath) else { return }
        pushFamilyAddVc(vm, addType: .edit)
    }
    
    func familyViewCell(willBindCard cell: FamilyViewCell) {
        guard let indexPath = tableView.indexPath(for: cell),
            let vm = viewModel?.viewModel(for: indexPath) else { return }
        getBindCardList(vm)
    }
    
    private func pushFamilyAddVc(_ vm: FamilyRowViewModel, addType: FamilyAddType) {
        let addVc = FamilyAddViewController(patientId: vm.id, addType: addType)
        addVc.title = addType.title
        navigationController?.pushViewController(addVc, animated: true)
        addVc.updateClosure = { [weak self] in
            guard let self = self else { return }
            self.loadData()
        }
    }
    
    /// 查询是否有卡
    private func getBindCardList(_ vm: FamilyRowViewModel) {
        activityView.startAnimating()
        BindCardViewModel.getBindCardList(patientId: vm.patientId, success: { model in
            self.activityView.stopAnimating()
            self.cardVm = BindCardViewModel(model: model)
            
            switch self.cardVm.status {
            case .canBind: self.showBindCardAlert(vm)
            case .changePhone: self.showChangePhoneView(vm)
            case .noCard: self.showAddCardAlert()
            }
            
        }) { errorMsg in
            self.activityView.stopAnimating()
            HUDTool.showError(message: errorMsg)
        }
    }
    
    /// 提示绑卡alert
    private func showBindCardAlert(_ vm: FamilyRowViewModel) {
        AlertTool.showAlert(self, message: "您（\(vm.name)）在医院曾创建过卡号，请关联绑定", sureTitle: "绑卡", cancelTitle: "暂不绑卡", type: .double, sureHandler: { (_) in
            self.showSendCodeView(self.cardVm)
        })
    }
    
    /// 提示增卡alert
    private func showAddCardAlert() {
        AlertTool.showAlert(self, title: "是否在医院里新建自费就诊卡", message: "暂不支持线上开医保卡，如需要开医保卡，请前往医院", sureTitle: "新增就诊卡", cancelTitle: "暂不新增", type: .double, sureHandler: { (_) in
            self.showSendCodeView(self.cardVm)
        })
    }
    
    /// 显示发送短信验证码view
    private func showSendCodeView(_ vm: BindCardViewModel) {
        let showView = UINib.loadViewFrom(BindCardMainView.self)
        showView.show(vm: vm)
        showView.delegate = self
    }
    
    /// 显示修改手机view
    private func showChangePhoneView(_ vm: FamilyRowViewModel) {
        let changePhoneView = UINib.loadViewFrom(YSGBindCardChangePhoneView.self)
        changePhoneView.show(vm: cardVm)
        changePhoneView.handleClosure = { [weak self] (action, value) in
            guard let self = self else { return }
            switch action {
            case .sendSmsCode:
                self.sendSmsCode(phone: self.cardVm.hosPhoneNo)
            case .confirmIdentity:
                self.bindCard(phone: self.cardVm.hosPhoneNo, smsCode: value)
            case .applyforModification:
                self.pushChangephoneVc(vm)
            }
        }
    }
    
    private func pushChangephoneVc(_ vm: FamilyRowViewModel) {
        let changePhoneVc = ChangePhoneController(with: vm, reservedPhone: cardVm.hosPhoneNoFour)
        navigationController?.pushViewController(changePhoneVc, animated: true)
        changePhoneVc.handlerClosure = { [weak self] in
            guard let self = self else { return }
            self.tableView.mj_header?.beginRefreshing()
        }
    }
    
    /// 发送短信验证码
    private func sendSmsCode(phone: String) {
        BindCardViewModel.sendSmsCode(phone: phone) { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: "获取验证码失败")
            case .success:
                HUDTool.show(message: "验证码已发送")
            }
        }
    }
    
    /// 绑卡
    private func bindCard(phone: String, smsCode: String) {
        BindCardViewModel.bindCard(patientId: cardVm.patientId, phone: phone, code: smsCode) { (errorMsg, code) in
            switch code {
            case .failure:
                HUDTool.showError(message: errorMsg)
            case .success:
                HUDTool.show(message: "绑卡成功")
                self.tableView.mj_header?.beginRefreshing()
            }
        }
    }
}

extension FamilyViewController: BindCardMainViewDelegate {
    func didSendCodeMsg() {
        sendSmsCode(phone: cardVm.phone)
    }
    
    func didEndEdit(textField: UITextField) {
        self.cardVm.msgCode = textField.text!
    }
    
    func didSureAddCard(msgCode: String) {
        switch cardVm.status {
        case .canBind:
            bindCard(phone: cardVm.phone, smsCode: msgCode)
        case .noCard:
            BindCardViewModel.addCard(patientId: cardVm.patientId, code: msgCode) { (errorMsg, code) in
                switch code {
                case .failure:
                    HUDTool.showError(message: errorMsg)
                case .success:
                    HUDTool.show(message: "新增卡片成功")
                    self.tableView.mj_header?.beginRefreshing()
                }
            }
        default: break
        }
    }
}
